package com.liufei.class03;

import com.liufei.class02.Code03_Comp;

import java.util.Arrays;

public class Code01_BSExist {



    // 二分遍历查找
    public static boolean binarySearch(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int L = 0;
        int R = nums.length - 1;
        while (L <= R) {
            // int mid = (L + R) >> 1;  直接相加再除以2，相加的过程数据可能会溢出，一般这样写 L + (R - L) / 2
            int mid = (L + R) / 2;
            if (nums[mid] == target) {
                return true;
            } else if (nums[mid] < target) {
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        return false;
    }

    // 正常遍历查找
    public static boolean search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int maxLen = 1000;
        int maxValue = 1000;
        int times = 10000;
        boolean succeed = true;
        for (int i = 0; i < times; i++) {
            int[] nums = Code03_Comp.lenRandomValueRandom(maxLen, maxValue);
            Arrays.sort(nums);
            int target = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            boolean b1 = binarySearch(nums, target);
            boolean b2 = search(nums, target);
            if (b1 != b2) {
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "success" : "failed");
    }
}
